package com.hz.mybatistest.service.impl;

import com.hz.mybatistest.helper.StringHelper;
import com.hz.mybatistest.mapper.UserMapper;
import com.hz.mybatistest.model.entiy.UserEntity;
import com.hz.mybatistest.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void addUser(String username, String realname, String studentId, String password, int userType) {
        // baseinfo
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        userEntity.setRealname(realname);
        userEntity.setStudent_id(studentId);

        // create pwd
        String pwdSalt = UUID.randomUUID().toString().replace("-", "");
        String pwd = StringHelper.generateMD5(password + pwdSalt);
        userEntity.setPwd(pwd);
        userEntity.setPwd_salt(pwdSalt);
        userEntity.setUser_type(userType);
        userEntity.setPwd_error_count(0);
        userEntity.setPwd_valid_date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000);
        userMapper.addUser(userEntity);
    }

    @Override
    public List<UserEntity> findAll() {
        return userMapper.findAll();
    }

    @Override
    public void deleteUser(int userId) {
        userMapper.deleteUserById(userId);
    }

    @Override
    public Boolean login(String username, String password) {
        //1,find user by username
        UserEntity userEntity = userMapper.findUserByUsername(username);
        if (userEntity == null) {
            return false;
        }

        // 2,get encrypted password,get pwdSalt
        String pwd = userEntity.getPwd();
        String pwdSalt = userEntity.getPwd_salt();

        // 3, password -> encrypted password
        String inputPwd = StringHelper.generateMD5(password + pwdSalt);

        //  4,is password == encrypted password
        if(!pwd.equals(inputPwd)) {
            return false;
        }

        redisTemplate.opsForValue().set("session_" + username, userEntity.toString(), 10, TimeUnit.MINUTES);
        return true;
    }
}
